import {useAtom} from "jotai";
import {selectedIdsAtom} from "../../store/atoms";

import {Question} from "../../types";
import BaseQuesItem from "../BaseQuesItem";
import {useEffect, useState} from "react";

interface Props {
    className?: string;
}

/**
 * 已选考题列表，带删除角标
 * @param className 扩展
 */
function SelectedPageQuesList({className = ''}: Props) {
    // 全局状态：已勾选的题目id集合
    const [selectedIds, setSelectedIds] = useAtom(selectedIdsAtom);
    const toggleSelectedIds = (id: number) => {
        const newList = selectedIds.filter(i => i !== id);
        setSelectedIds(newList);
        console.log('Removed:', id, 'Result:', newList);
    }
    // 内部状态：当前包含的考题列表
    const [quesList, setQuesList] = useState<Question[]>([]);
    useEffect(() => {
        window.ipcRender.invoke('ques:getSelected', {
            ids: selectedIds,
        }).then((res) => {
            setQuesList(res);
            console.log("当前页考题id:", res.map((q: Question) => q.id));
        })
    }, [selectedIds]);

    return (
        <div className={`m-2 ${className}`}>
            {quesList.map((question) => (
                <div key={question.id} className="flex items-start gap-2">
                    {/* 左侧题目 */}
                    <div className="flex-1">
                        <BaseQuesItem question={question}/>
                    </div>
                    {/* 右侧删除按钮 */}
                    <button className="btn btn-square btn-error text-error-content mt-5"
                            onClick={() => toggleSelectedIds(question.id)}>
                        <span className="fa fa-trash fa-lg"/>
                    </button>
                </div>
            ))}
        </div>
    )
}

export default SelectedPageQuesList;